package com.starsea.book.ui.newpage.weidget.flow

import android.content.Context
import android.util.AttributeSet
import com.starsea.book.ui.newpage.entity.FlowContentEntity
import com.starsea.book.ui.newpage.weidget.flow.FlowAdapter.OnDataChangedListener

/**
 * @author Lee
 * @createTime 2023-10-31 16 GMT+8
 * @desc :
 */
open class FlowListView : FlowLayout, OnDataChangedListener {
  protected var flowAdapter: FlowAdapter<FlowContentEntity>? = null

  constructor(context: Context) : super(context)
  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
  constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
  )

  fun setAdapter(tagAdapter: FlowAdapter<FlowContentEntity>?) {
    flowAdapter = tagAdapter
    flowAdapter!!.setOnDataChangedListener(this)
    updateView()
  }

  override fun onChanged() {
    updateView()
  }

  open fun updateView() {
    removeAllViews()
    if (null == flowAdapter) {
      throw RuntimeException("adapter cannot be empty")
    }
    val count = flowAdapter!!.count

    for (i in 0 until count) {
      val tagView = flowAdapter!!.getView(this, flowAdapter!!.getItem(i)!!, i)
      tagView!!.tag = flowAdapter!!.getItem(i)
      flowAdapter!!.initView(tagView, flowAdapter!!.getItem(i)!!, i)
      addView(tagView)
    }
  }
}
